<?php

namespace app\admin\controller\statistical;

use app\common\controller\Backend;
use app\admin\model\AdminNotice;
use app\admin\model\WorkTemplate;
use app\admin\model\Admin;
use think\Db;
/**
 * 浮动性工作上报审核管理
 *
 * @icon fa fa-circle-o
 */
class WorkReview extends Backend
{

    /**
     * SalaryBenchmark模型对象
     * @var \app\admin\model\SalaryBenchmark
     */
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\WorkTemplateLog();
        $this->view->assign("type_arr", (new WorkTemplate())->type_arr);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['admin','template'])
                ->where('work_template_log.status','in',[3,5,6])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->first_trial_admin_name = Admin::where('id',$row->first_trial_admin_id)->value('nickname');
                $row->end_trial_admin_name = Admin::where('id',$row->end_trial_admin_id)->value('nickname');
                $row->visible(['id','admin_id','type','teacher_type','select_time','status','reject_reason',
                    'first_trial_reject_reason','first_trial_admin_name','first_trial_time',
                    'end_trial_reject_reason','end_trial_time','end_trial_admin_name','create_time','admin','template']);

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 通过
     */
    public function pass_through($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            Db::startTrans();
            try {
                $temp_info = $this->model->where(['temp_id'=>$row->temp_id,'temp_item_id'=>$row->temp_item_id,'status'=>5])->find();
                if(!empty($temp_info))exception('同一个模板同一个日期已经有通过的数据');
                AdminNotice::create(array('admin_id'=>$row->admin_id,'status'=>'3','content'=>'您提交的工作上报已终审通过'));
                $res = $row->save(array('status'=>'5','end_trial_admin_id'=>$this->auth->id,'end_trial_time'=>date('Y-m-d H:i:s')));
                if (!$res)exception('审核成功');
                Db::commit();
            }  catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }

        return $this->view->fetch();
    }

    /**
     * 驳回
     */
    public function reject($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    $params['status'] = '6';
                    $params['end_trial_admin_id'] = $this->auth->id;
                    $params['end_trial_time'] = date('Y-m-d H:i:s');
                    $result = $row->allowField(true)->save($params);
                    AdminNotice::create(array('admin_id'=>$row->admin_id,'status'=>'4','content'=>'您提交的工作上报被终审驳回  驳回原因：'.$params['end_trial_reject_reason']));
                    if(!$result)exception('驳回失败');
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    
    
     /**
     * 批量审核
     */
    public function batch_examine()
    {
        Db::startTrans();
        try {
            $idStr = $this->request->post('ids','');
            $type = $this->request->post('type','pass');
            $ids = json_decode($idStr,true);
            if(empty($ids))exception('请勾选您需操作的内容');

            if($type == 'pass'){
                foreach ($ids as $v){
                    $info = $this->model->get($v);
                    if (!$info)exception('未找到ID:'.$v.'的内容');
                    if ($info['status'] != 3)exception('ID:'.$v.'的状态不正确，请先移除');

                    $res = $info->save(array('status'=>'5','end_trial_admin_id'=>$this->auth->id,'end_trial_time'=>date('Y-m-d H:i:s')));
                    AdminNotice::create(array('admin_id'=>$info->admin_id,'status'=>'3','content'=>'您提交的工作上报已终审审通过'));
                    if (!$res)exception('ID:'.$v.'审核失败');
                }
            }else{
                foreach ($ids as $v) {
                    $info = $this->model->get($v);
                    if (!$info)exception('未找到ID:'.$v.'的内容');
                    if ($info['status'] != 3)exception('ID:'.$v.'的状态不正确，请先移除');
                    $end_trial_reject_reason = '提交信息不完整';

                    $arr = array(
                        'status' => 6,
                        'end_trial_admin_id' => $this->auth->id,
                        'end_trial_time' => date('Y-m-d H:i:s'),
                        'end_trial_reject_reason' => $end_trial_reject_reason,
                    );
                    $res = $info->allowField(true)->save($arr);
                    AdminNotice::create(array('admin_id'=>$info->admin_id,'status'=>'4','content'=>'您提交的工作上报被终审驳回  驳回原因：'.$end_trial_reject_reason));
                    if (!$res) exception('ID:'.$v.'驳回失败');
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('操作成功');
    }


}
